// pages/car/message/message.js
const app = getApp()
var tab = require('../../../components/tabbar/tabbar.js');
// var cityData = require('../../../utils/citydatas.js');
Page({

    data: {
        nav:[
            '资源',
            '资讯'
        ],// 头部导航
        navId:0,
        resourceList:[],// 资源列表
        active: 0, 
        recommend:[],// 资讯列表
        recommendId: 1,// 资讯列表id
        page: 1, //资讯列表页数
        show: false,// 时间
        region:'', // 时间显示
        currentDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          } else if (type === 'day') {
            return `${value}日`;
          }
          return value;
        },
        index: '',// 显示状态
        toolbar: 'false',
        showLoad: false, // 装货地弹窗
        type: '',// 判断点击哪个省市区
        province_zid: '', // 装货省
        city_zid: '', // 装货市
        area_zid: '', // 装货区
        type_zid: '', //判断装货区是否滑动
        regionTwo:[],
        showLoads: false,// 卸货地弹窗
        province_xid: '', // 卸货省
        city_xid: '', // 卸货市
        area_xid: '', // 卸货区
        type_xid: '', //判断卸货区是否滑动
        regionThree:[],
        citysData: [], 
        provinces_z: [],
        citys_z: [],
        areas_z: [],
        value_z: [0,0,0],
        provinces_x: [],
        citys_x: [],
        areas_x: [],
        value_x: [0,0,0],
        showFour: false,// 车型弹出层
        longList:[], // 车长数组
        longId: null, // 车长id
        longName: '', // 车长名字
        carLonglId: '', // 获取车长id
        modelList:[],// 车型数组
        modelId: null, // 车型id
        modelName: '', // 车型name
        carModellId:'', // 获取车型id
        regionFour:[], // 车型显示
        newsList:[],// 资讯导航
        newsId:0, // 资讯导航id
        status: '',
        provinces_zids: '',
        citys_zids: '',
        areas_zids: '',
        provinces_xids: '',
        citys_xids: '',
        areas_xids: ''
    },
    onLoad: function (options) {
        tab.tabbar("tabBar", 1, this)//0表示第一个tabbar
        this.newsList();// 资讯导航
        this.resourceList(); // 资源列表
        this.getCarType();// 车型
        this.getCarLong(); // 车长
        this.getAddress(); //获取地区
        // this.initData(); // 装货地省市区 
        // this.initDatas(); //卸货地省市区 
    },
     // 下拉刷新
     onPullDownRefresh: function () {
        if(this.data.navId == 0){
            wx.showNavigationBarLoading();
            this.setData({
                // 把所选内容清空/重新赋值
                page: 1,
                region:'', // 时间显示
                // province_zid: '', //装货省
                provinces_z: [],
                provinces_x: [],
                // city_zid: '', //装货市
                // area_zid: '', //装货区
                // province_xid: '', //卸货省
                // city_xid: '', //卸货市
                // area_xid: '', //卸货区
                carLonglId: '', // 车长
                carModellId: '', // 车型
                longId: null,
                modelId: null,
                longName: '',
                modelName: '',
                provinces_zids: '',
                citys_zids: '',
                areas_zids: '',
                provinces_xids: '',
                citys_xids: '',
                areas_xids: ''
            })
            this.resourceList(); // 货主列表
            this.getAddress();
            this.initData(); // 装货地省市区
            this.initDatas(); //卸货地省市区
        } else if(this.data.navId == 1){
            wx.showNavigationBarLoading();
            this.setData({
                page: 1,
                recommendId: this.data.status
            })
            this.recommendList(this.data.page,this.data.recommendId); //资讯列表
        }
    },
    // 加载更多
    onReachBottom: function() {
        if(this.data.navId == 0){
            wx.showLoading({
                title: '加载中···',
            })
            setTimeout(() => {
                this.resourceList(this.data.page);
            }, 500);
        } else if(this.data.navId == 1){
            wx.showLoading({
                title: '加载中···',
            })
            setTimeout(() => {
                this.recommendList(this.data.page,this.data.recommendId);
            }, 500); 
        }
    },
    // 头部导航 点击
    navClick(event){
        var index = event.currentTarget.dataset.index;
        var recommendId = 1;//资讯列表id
        var page = this.data.page;
        this.setData({
          navId: index,
          newsIds: 0,
          page: 1
        })
        this.recommendList(page,recommendId);
    },
    // 资讯导航
    newsList(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/articletop',
            method: 'GET',
            data:{},
            success: res => {
                this.setData({
                    newsList: res.data.data
                })
            },
            fail: err => {
                console.log(err)
            }
        })   
    },
    // 资讯 分类点击
    newsClick(event){
        wx.showLoading({
            title:'加载中···'
        })
        var index = event.currentTarget.dataset.index;
        var id = event.currentTarget.dataset.id;
        this.setData({
            newsId : index,
            recommendId:id,
            page: 1,
            recommend:''
        })
        this.recommendList(this.data.page,this.data.recommendId)     
    },
    //时间 显示
    showPopup() {
        this.setData({ 
            show: true,
            showLoad: false,
            showLoads: false,
            showFour: false,
            index:1
        });
    },
    // 关闭
    onClose() {
        this.setData({
            show: false,
            timeColor:'#333',
            index:0
        });
    },
    // 确认
    onConfirm(event) {
        if(event.detail == ""){
            return ;
        }
        var date = this.getDate(event.detail);
        var arr = date.split(" ");
        var time = arr[0].split("-")
        const { picker, value, index } = event.detail;
        this.setData({
            show: false,
            timeColor:'#333',
            region: event.detail,
            index: 0,
            page:1,
        });
        let year = time[0]; 
        var month = time[1];
        var day = time[2];
        if(month<10){ 
            month = '0'+month 
        }
        if( parseInt(day)<10){
            day = '0'+day  
        }
        this.setData({
            region:  year + '-' + month + '-' +  day
        })
        this.resourceList()
        console.log(this.data.region)
    },
    // 取消
    onCancel() {
        this.setData({ 
            show: false,
            timeColor:'#333',
            index: 0
        });
    },
    // 装货地
    initData: function(){
        var provinces_z = [];
        var citys_z = [];
        var areas_z = [];

        this.data.citysData.forEach(function(province,i){
            provinces_z.push(province.name);
            if(i===0){
                citys_z.push(province.citys[i].name);
                citys_z.push(province.citys[1].name);
                areas_z = province.citys[i].areas;
            }
        });
        this.setData({
            provinces_z: provinces_z,
            citys_z: citys_z,
            areas_z: areas_z
        });
    },
    // 装货地 滑动
    bindChange: function(e){
        console.log(e);
        var citysData = this.data.citysData;
        var value = this.data.value_z;
        var current_value = e.detail.value;
        var citys = [];

        var provinceObj = {};
        var cityObj = {};

        provinceObj = citysData[current_value[0]];

        if (value[0] !== current_value[0]) {
            // 滑动省份
            provinceObj.citys.forEach(function(v){
                citys.push(v.name);
            });
            this.setData({
                citys_z: citys
            });

            cityObj = provinceObj.citys[0];
            this.setData({
                areas_z: cityObj.areas,
                value_z: [current_value[0],0,0]
            });

        }else if(value[0] === current_value[0] && value[1] !== current_value[1]){
            // 滑动城市
            if(current_value[1]>=provinceObj.citys.length){
                // 数据不存在 跳过
                return;
            }
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                areas_z: cityObj.areas,
                value_z: [current_value[0],current_value[1],0]
            });
        }else{
            // 滑动区县
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                value_z: current_value
            });
        }
        this.setData({
            province_zid: provinceObj.name, // 卸货省
            city_zid: cityObj.name, // 卸货市
            area_zid: cityObj.areas[this.data.value_z[2]], // 卸货区
            type_zid: 1
        })
    },
    // 显示装货地
    showLoad(e) {
        this.setData({
            type: e.currentTarget.dataset.type,
            showLoad: true,
            show: false,
            showLoads: false,
            showFour: false,
            index: 2
        })
    },
    // 关闭装货地
    onCloses(){
        this.setData({
            showLoad: false,
            index:0
        })
    },
    // 取消装货地
    loadCancel() {
        this.setData({
            showLoad: false,
            index: 0,
        })
    },
    // 装货地确定按钮
    loadConfirm(e) {
        console.log(this.data.type_zid)
        if(this.data.type_zid == ''){
            this.setData({
                province_zid: '北京市',
                provinces_zids: '北京市',
                city_zid: ''
            })
        }else{
            if(this.data.city_zid == '全部'){
                this.setData({
                    city_zid: '',
                    area_zid: ''
                })
            }
            if(this.data.area_zid == '全部'){
                this.setData({
                    area_zid: '',
                })
            }
            this.setData({
                province_zid: this.data.province_zid,
                city_zid: this.data.city_zid,
                area_zid: this.data.area_zid,
                provinces_zids: this.data.province_zid,
                citys_zids: this.data.city_zid,
                areas_zids: this.data.area_zid
            })
        }
        this.setData({
            showLoad: false,
            page: 1,
            index: 0
        })
        this.resourceList()     
    },
    // 卸货地
    initDatas: function(){
        var provinces_x = [];
        var citys_x = [];
        var areas_x = [];
        this.data.citysData.forEach(function(province,i){
            provinces_x.push(province.name);
            if(i===0){
                citys_x.push(province.citys[i].name);
                citys_x.push(province.citys[1].name);
                areas_x = province.citys[i].areas;
            }
        });
        this.setData({
            provinces_x: provinces_x,
            citys_x: citys_x,
            areas_x: areas_x
        });
    },
    // 卸货地 滑动
    bindChanges: function(e){
        var citysData = this.data.citysData;
        var value = this.data.value_x;
        var current_value = e.detail.value;
        var citys = [];

        var provinceObj = {};
        var cityObj = {};

        provinceObj = citysData[current_value[0]];

        if (value[0] !== current_value[0]) {
            // 滑动省份
            provinceObj.citys.forEach(function(v){
                citys.push(v.name);
            });
            this.setData({
                citys_x: citys
            });

            cityObj = provinceObj.citys[0];
            this.setData({
                areas_x: cityObj.areas,
                value_x: [current_value[0],0,0]
            });

        }else if(value[0] === current_value[0] && value[1] !== current_value[1]){
            // 滑动城市
            if(current_value[1]>=provinceObj.citys.length){
                // 数据不存在 跳过
                return;
            }
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                areas_x: cityObj.areas,
                value_x: [current_value[0],current_value[1],0]
            });
        }else{
            // 滑动区县
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                value_x: current_value
            });
        }
        this.setData({
            province_xid: provinceObj.name, // 卸货省
            city_xid: cityObj.name, // 卸货市
            area_xid: cityObj.areas[this.data.value_x[2]], // 卸货区
            type_xid: 1
        })
    },
     //显示卸货地
    showLoads(e) {
        this.setData({
            type: e.currentTarget.dataset.type,
            showLoads: true,
            show: false,
            showLoad: false,
            showFour: false,
            index: 3
        })
    },
    // 关闭卸货地
    onClosesTwo(){
        this.setData({
            showLoads: false,
            index: 0,
        })
    },
    //取消卸货地
    loadCancels() {
        this.setData({
            showLoads: false,
            index: 0,
        })
    },
    //卸货地确定按钮
    loadConfirms(e) {
        console.log(this.data.type_xid)
        if(this.data.type_xid == ''){
            this.setData({
                province_xid: '北京市',
                provinces_xids: '北京市',
                city_xid: ''
            })
        }else{
            if(this.data.city_xid == '全部'){
                this.setData({
                    city_xid: '',
                    area_xid: ''
                })
            }
            if(this.data.area_xid == '全部'){
                this.setData({
                    area_xid: '',
                })
            }
            this.setData({
                province_xid: this.data.province_xid,
                city_xid: this.data.city_xid,
                area_xid: this.data.area_xid,
                provinces_xids: this.data.province_xid,
                citys_xids: this.data.city_xid,
                areas_xids: this.data.area_xid
            })
        }   
        this.setData({
            showLoads: false,
            page: 1,
            index: 0
        })
        this.resourceList()     
    },
    // 车型 显示
    showPopupFour() {
        this.setData({ 
            showFour: true,
            show: false,
            showLoad: false,
            showLoads: false,
            index: 4
        });
    },
    // 关闭
    onCloseFour() {
        this.setData({ 
            showFour: false,
            modelColor: '#333',
            index: 0
        });
    },
    // 确认
    onConfirmFour(event) {
        const { picker, value, index } = event.detail;
        if( this.data.longName==''){
            wx.showToast({
              title: '请选择车长',
              icon: 'none'
            })
            return false
        } else if(this.data.modelName==''){
            wx.showToast({
                title: '请选择车型',
                icon: 'none'
            })
            return false
        } else {
            this.setData({ 
                showFour: false,
                regionFour: this.data.longName + '/' + this.data.modelName,
                page:1,
                index: 0,
            });
        }
        this.resourceList()
    },
    // 取消
    onCancelFour(){
        this.setData({ 
            showFour: false,
            modelColor: '#333',
            longId: null,
            modelId: null,
            index: 0
        });
    },
    // 车长 点击
    modelClick(event){
        var index = event.currentTarget.dataset.index;
        var name = event.currentTarget.dataset.name;
        var id = event.currentTarget.dataset.id;
        this.setData({
          longId : index,
          longName: name,
          carLonglId: id
        })
        console.log(this.data.carLonglId)
    },
    // 车型 点击
    modelClickTwo(event){
        var index = event.currentTarget.dataset.index;
        var name = event.currentTarget.dataset.name;
        var id = event.currentTarget.dataset.id;
        this.setData({
            modelId : index,
            modelName: name,
            carModellId: id
        })
    },
    // 车型
    getCarType(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/getcar',
            method: 'GET',
            data:{
            },
            success: res => {
                console.log(res)
                this.setData({
                    modelList: res.data.data
                })
            },
            fail: err => {
              console.log(err)
            },
        })  
    },
    // 车长
    getCarLong(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/conductor',
            method: 'GET',
            data:{},
            success: res => {
                console.log(res)
                this.setData({
                    longList: res.data.data
                })
            },
            fail: err => {
              console.log(err)
            }
        })  
    },
    //获取地区
    getAddress() {
        wx.request({
            url: app.globalData.url + 'api/v1/news/regions',
            method: 'GET',
            success: res => {
                console.log(res)
                this.setData({
                    citysData: res.data.data
                })
                this.initData();
                this.initDatas();
            },
            fail: err => {
                console.log(err)
            }
        })
    },
    // 资讯列表
    recommendList(page,recommendId){
        wx.showLoading({
            title:'加载中···'
        })
        this.setData({
            status: recommendId
        })
        var page = this.data.page;
        wx.request({
            url: app.globalData.url + 'api/v1/news/articlelist',
            method: 'GET',
            data:{
                id: recommendId,
                page: page,
                limit: 10
            },
            success: res => {
                console.log(res)
                if( res.data.code == 200 ){
                    if ( page >1) {
                        if( res.data.data.data.info != ''){
                            this.setData({
                                recommend: this.data.recommend.concat(res.data.data.data.info),
                                page: page + 1
                            })
                        }
                    } else {
                        this.setData({
                            recommend: res.data.data.data.info,
                             page: page + 1
                        })
                    }
                } else {
                    setTimeout(() => {
                        wx.showToast({
                            title: '没有更多数据',
                            icon: 'none',
                            mask: true
                        })
                    },500)
                }
            },
            fail: err => {
                console.log(err)
            },
            complete: () => {
                wx.hideLoading()
                wx.stopPullDownRefresh();
                wx.hideNavigationBarLoading();
            }
        })
    },
    // 资源列表
    resourceList(){
        var page = this.data.page;
        wx.showLoading({
            title: '加载中···',
        })
        wx.request({
            url: app.globalData.url + 'api/v1/owner/owner/resourceslist',
            method: 'GET',
            data:{
                owner_id: wx.getStorageSync('id'),
                time:this.data.region,
                province_zid : this.data.provinces_zids,
                city_zid: this.data .citys_zids,
                area_zid:this.data.areas_zids,
                province_xid : this.data.provinces_xids,
                city_xid: this.data .citys_xids,
                area_xid: this.data.areas_xids,
                cartype: this.data.carModellId, // 车长
                conductor_id: this.data.carLonglId, // 车型
                page: page,
                limit: 10
            },
            success: res => {
                if( res.data.code == 200 ){
                    if ( page >1) {
                        if( res.data.data.data.info != ''){
                            this.setData({
                                resourceList: this.data.resourceList.concat(res.data.data.data.info),
                                page: page + 1
                            })
                        }
                    } else {
                        this.setData({
                            resourceList: res.data.data.data.info,
                            page: page + 1
                        })
                    }
                } else {
                    setTimeout(() => {
                        wx.showToast({
                            title: '没有更多数据',
                            icon: 'none',
                            mask: true
                        })
                    },500)
                }
            },
            fail: err => {
              console.log(err)
            },
            complete: () => {
                wx.hideLoading()
                wx.stopPullDownRefresh();
                wx.hideNavigationBarLoading();
            }
        })
    },
    // 跳转资讯详情
    goTipsDetail(event){
        var id = event.currentTarget.dataset.id;
        wx.navigateTo({
          url: "/pages/infor/infor?id=" + id
        })
    },
    // 打电话
    tell:function(event){
        var phone = event.currentTarget.dataset.phone
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    // 时间戳
    getDate(unixtime) {
        var dateTime = new Date(parseInt(unixtime))
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        // var hour = dateTime.getHours();
        // var minute = dateTime.getMinutes();
        // var second = dateTime.getSeconds();
        var now = new Date();
        var now_new = Date.parse(now.toDateString()); //typescript转换写法
        var milliseconds = now_new - dateTime;
        var timeSpanStr = year + '-' + month + '-' + day 
        return timeSpanStr;
    },
     /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    } 
})